<!--
 * @Description: 模型列表
 * @Author: qingyang
 * @Date: 2022-01-10 16:04:17
 * @LastEditors: qingyang
 * @LastEditTime: 2023-06-26 10:17:44
-->
<template>
  <div class="my-model-list-container">
    <CPageTable @register="registerPage" v-model:searchForm="searchForm" v-loading="copyLoading">
      <template #headerRightButton>
        <el-button
          v-if="showRecycleBtn"
          @click="handleRecycle"
          v-btnPermission="'PCF_RECYCLE_VIEW'"
        >
          回收站 {{ recycleCount }}
        </el-button>
        <el-button @click="handleAdd" type="primary" v-btnPermission="'PCF_MODEL_CREATE'">
          <CIcon type="c-xian-xinjian" class="g-mr4"></CIcon> 创建模型
        </el-button>
      </template>

      <template #modelInfo="{ scope }">
        <CTableColumn
          :main-text="scope.row.modelName"
          :sub-text="`编码：${empty(scope.row.modelCode)}`"
          sub-text-color="#435970"
          :is-link="hasBtnPermission('PCF_MODEL_VIEW')"
          @link-click="goDetail(scope.row)"
        >
          <template #third>
            <div class="model-tag-wrap" v-if="scope.row.tag">
              <div
                class="model-tag"
                v-for="(item, index) in renderTags(scope.row.tag)"
                :key="index"
                >{{ item }}</div
              >
            </div>
          </template>
        </CTableColumn>
      </template>
      <template #type="{ scope }">
        <CTableColumn
          :main-text="ModelTypeMap[scope.row.modelType]"
          :sub-text="StandardDetailMap[scope.row.standard]"
        ></CTableColumn>
      </template>
      <template #creator="{ scope }">
        <CTableColumn
          :main-text="scope.row.creator"
          :sub-text="scope.row.createTime"
        ></CTableColumn>
      </template>
      <template #statusSlot="{ scope }">
        <el-tag :type="renderTag(scope.row.accountStatus)"
          >{{ AccountStatusPCFMap[scope.row.accountStatus] }}
        </el-tag>
        <el-tooltip
          content="模型数据有更新，前往核算页面获取最新核算结果"
          v-if="scope.row.accountChangeFlag"
        >
          <CIcon type="c-xian-jinggao" class="g-ml5 jinggao-icon-style"></CIcon>
        </el-tooltip>
      </template>
      <template #op="{ scope }">
        <CTableButtonGroup :buttons-config="getTableButtonsConfig(scope.row)" />
      </template>
    </CPageTable>
    <RecycleDetail
      v-model:visible="showRecycle"
      :id="selectId"
      @refresh="handleRefresh"
    ></RecycleDetail>
  </div>
</template>
<script lang="ts">
export default {
  name: 'MyModelList'
};
</script>
<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue';
import { CPageTable, useCPageTable, CPageTableProps } from '@/components/CPageTable';
import { useModelList, useRecycle } from './useModelList';
import { empty } from '@/utils/index';
import { useMessage } from '@/hooks/useMessage';
import { useRouter } from 'vue-router';
import { copyModel, delModel } from '@/apis/pcf/myModel/modelList';
import { useKeepAliveRefresh } from '@/hooks/useKeepAliveRefresh';
import { IModelListItem } from '@/apis/pcf/myModel/model/modelManage';
import type { TableButtonItem } from '@/components/CTable';
import { CTableColumn, CTableButtonGroup } from '@/components/CTable';
import RecycleDetail from './components/RecycleDetail/index.vue';
import { useDebounceFn } from '@vueuse/core';

import {
  ModelTypeMap,
  StandardDetailMap,
  AccountStatusPCFMap,
  AccountStatusPCFEnum
} from '@/constants/enum';
import { hasBtnPermission } from '@/directives/btnPermission';

const { createConfirm, createMessage } = useMessage();
const router = useRouter();
const { searchOptions, searchForm, tableOptions, tableFieldsSetting, isFinishedAutomobileModel } =
  useModelList();
const { recycleCount, loadRecycleCount, showRecycleBtn } = useRecycle();
const options = reactive<CPageTableProps>({
  title: isFinishedAutomobileModel ? '整车碳足迹模型' : '零部件组件模型',
  searchOptions: searchOptions,
  tableOptions,
  tableFieldsSetting,
  enableFieldsSetting: true
});

const handleAdd = () => {
  const type = isFinishedAutomobileModel ? 'finishedAutomobileModel' : 'partsModel';
  router.push(`/myModel/addModel?type=${type}`);
};
function getTableButtonsConfig(row: any): TableButtonItem[] {
  return [
    {
      text: '查看',
      btnPermission: 'PCF_MODEL_VIEW',
      onClick: () => goDetail(row)
    },
    {
      text: '复制',
      btnPermission: 'PCF_MODEL_COPY',
      onClick: () => handleCopy(row)
    },
    {
      text: '删除',
      btnPermission: 'PCF_MODEL_DELETE',
      onClick: () => deleteClick(row)
    }
  ];
}

const [registerPage, { refresh, setProps }] = useCPageTable(options);
onMounted(() => {
  loadRecycleCount();
});
const copyLoading = ref(false);
const copyClick = async (row: IModelListItem & { copyLoading: boolean }) => {
  copyLoading.value = true;
  row.copyLoading = true;
  try {
    await copyModel(row.modelNo);
    createMessage.success(`${row.modelName}复制成功！`);
    refresh(true);
  } finally {
    row.copyLoading = false;
    copyLoading.value = false;
  }
};
const handleCopy = useDebounceFn(copyClick, 300);
const deleteClick = (row: IModelListItem) => {
  createConfirm(
    '确定删除该模型吗？',
    '删除模型后将无法在平台内引用模型数据，对已引用数据无影响，删除后可在回收站内恢复模型。',
    {
      iconType: 'warning',
      confirmButtonText: '删除'
    }
  ).then(async () => {
    await delModel(row.modelNo);
    createMessage.success(`${row.modelName}删除成功！`);
    handleRefresh();
  });
};
const showRecycle = ref(false);
const selectId = ref('');
const handleRecycle = (row: IModelListItem) => {
  // 显示回收站
  selectId.value = row.modelNo;
  showRecycle.value = true;
};
const goDetail = (row: IModelListItem) => {
  const type = isFinishedAutomobileModel ? 'finishedAutomobileModel' : 'partsModel';
  router.push({
    path: `/myModel/modelFill/${row.modelNo}`,
    query: {
      type: type
    }
  });
};

useKeepAliveRefresh(refresh);
const renderTags = (tag: string) => {
  if (tag) {
    return tag.split(',');
  }
  return [];
};
const handleRefresh = () => {
  loadRecycleCount();
  refresh(true);
};
const renderTag = (status: keyof typeof AccountStatusPCFEnum) => {
  switch (status) {
    case AccountStatusPCFEnum.ACCOUNTED:
      return 'success';
    case AccountStatusPCFEnum.RUNNING:
      return '';
    case AccountStatusPCFEnum.NOT_ACCOUNT:
      return 'info';
    case AccountStatusPCFEnum.PART_ACCOUNTED:
      return 'warning';
    default:
      return '';
  }
};
</script>

<style lang="scss" scoped>
.my-model-list-container {
  min-height: 80%;
}
.jinggao-icon-style {
  color: #96a7b3;
  &:hover {
    color: #435970;
  }
}

.model-tag {
  min-width: 36px;
  height: 20px;
  padding: 0 6px;
  line-height: 20px;
  text-align: center;
  background: #eef1f5;
  border-radius: 3px;
  font-size: 12px;
  color: #5a739a;
  margin-bottom: 4px;
  margin-right: 4px;
}
.model-tag-wrap {
  display: flex;
  margin-top: 6px;
  flex-wrap: wrap;
}
</style>
